// 列表hooks
export function usePaginatedList(fetchFunction, initialQuery) {
  const list = ref([]);
  const pageNo = ref(1);
  const pageSize = ref(initialQuery.pageSize || 10);
  const noMoreData = ref(false);
  const loading = ref(false);
  const status = ref("more");
  status.value = "loading";
  const fetchList = (isRefresh = false) => {
    uni.showLoading(); // 加载
    if (isRefresh) {
      pageNo.value = 1;
      list.value = [];
      noMoreData.value = false;
      status.value = "loading";
    } else {
      status.value = "loading";
    }

    loading.value = true;
    let query = {
      ...initialQuery,
      pageNo: pageNo.value,
      pageSize: pageSize.value,
    };
    fetchFunction(query)
      .then((res) => {
        uni.hideLoading();
        uni.stopPullDownRefresh(); // 停止下拉刷新
        loading.value = false;
        if (res && res.code == 0) {
          if (res.data.records.length < pageSize.value) {
            noMoreData.value = true;
            status.value = "noMore";
          } else {
            status.value = "more";
          }
          if (isRefresh) {
            list.value = res.data.records;
          } else {
            list.value = [...list.value, ...res.data.records];
          }
          pageNo.value++;
        } else {
          tip.error(res.msg);
          status.value = "more";
        }
      })
      .catch(() => {
        loading.value = false;
        uni.hideLoading();
        uni.stopPullDownRefresh(); // 停止下拉刷新
        tip.error("数据获取失败");
        status.value = "more";
      });
  };

  const ReachBottom = () => {
    if (!noMoreData.value && !loading.value) {
      fetchList();
    }
  };

  const onPullDown = () => {
    fetchList(true);
  };

  return {
    list,
    loading,
    noMoreData,
    fetchList,
    ReachBottom,
    onPullDown,
    status,
  };
}
